package com.igeek.ch02.service;

import com.igeek.ch02.dao.UserDao;
import com.igeek.ch02.entity.User;
import com.igeek.ch02.utils.JDBCUtils;
import com.igeek.ch02.vo.PageVO;

import java.sql.SQLException;
import java.util.List;

/**
 * @Description TODO
 * @Author chenmin
 * @Version 1.0
 * @Date 2023/1/5 16:58
 */
public class UserService {

    private UserDao dao = new UserDao();

    //登录
    public User login(String name , String pwd){
        User user = null;
        try {
            user = dao.selectOne(name, pwd);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.close();
        }
        return user;
    }

    //注册
    public boolean register(User user){
        try {
            return dao.insert(user)>0? true:false;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.close();
        }
        return false;
    }

    //分页
    public PageVO<User> fenye(int current){
        PageVO<User> pageVO=null;
        try {
            int counts= dao.selectCounts();

            int myPages=counts%3==0?counts/3:(counts/3+1);

            int begin=(current-1)*3;

            List<User> users= dao.selectAll(begin);

            pageVO=new PageVO<>(current,counts,myPages,null,users);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JDBCUtils.close();
        }
        return pageVO;

    }

    //删除
    public boolean delete(int id){
        try {
            return dao.delete(id)>0?true:false;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JDBCUtils.close();
        }
        return false;
    }

    //更新
    public boolean update(User user){
        try {
            return dao.update(user)>0?true:false;
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtils.close();
        }
        return false;
    }

    //查看
    public User viewOne(int id){
        User user=null;
        try {
            return user=dao.selectOne(id);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JDBCUtils.close();
        }
        return user;
    }

}
